import { observable, action, autorun, toJS } from 'mobx';
import { WeaTools } from 'ecCom';
import { message, Modal } from 'antd';
import isEqual from 'lodash/isEqual';
import { WeaTableNew, WeaForm } from 'comsMobx';
import * as Apis from '../apis/customercard';
import * as API_CONTACT from '../apis/contact';
import { CrmContactStore } from './crmContactStore';
import { OutResourceStore } from './outResourceStore';
import { BatchShareStore } from './batchShareStore';
import { AddressManageStore } from './addressManageStore';
import { CrmMessageStore } from './crmMessageStore';
import { ContractManageStore } from './contractManageStore';
import { ContacterMapStore } from './contacterMapStore';

const { TableStore } = WeaTableNew;

import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export class CustomerCardStore {
    user = {};
    @observable title = getLabel(20323, '客户信息');
    contacterData = [];// 作为数据对比时使用
    @observable tabDatas = [];
    @observable detailTabKey = '1';
    detailTab;
    @observable loading = false;
    @observable loadingInfo = false;
    @observable customerId = '';
    @observable customerName = '';
    @observable rightLevel = '1';
    @observable currentPageState = 'readOnly';
    @observable rightMenu = [];
    @observable conditioninfo = [];
    conditioninfoEdit = [];
    conditioninfoRead = [];
    @observable contacterInfo = {};
    @observable crmInfoContactStore = new CrmContactStore();
    @observable crmOutResourceStore = new OutResourceStore();

    @observable remindInfo = {};
    @observable form = new WeaForm(); //
    @observable hasRight = false; // 权限
    @observable verified = false;
    // 共享设置
    @observable shareTableStore = new TableStore();
    @observable shareAuth = {
      hasRight: false,
      verified: false,
    }
    @observable shareStore = new BatchShareStore();
    // 修改记录
    @observable viewlogCondition = [];
    @observable viewlogForm = new WeaForm();
    @observable modifyTableStore = new TableStore();
    @observable modifyAuth = {
      hasRight: false,
      verified: false,
    }
    @observable showSearchAd = false;
    // 客户价值
    @observable evalAuth = {
      hasRight: false,
      verified: false,
    }
    @observable evalStandard = [];
    @observable evalDataSources = [];
    @observable evalDataSources = [];
    @observable evalParams = {};
    // 地址管理
    @observable addressManageStore = new AddressManageStore();
    // 客户留言
    @observable crmMessageStore = new CrmMessageStore();
    // 合同管理
    @observable contractStore = new ContractManageStore();

    @observable contacterMap = new ContacterMapStore();
    @observable shareCondition=[];
    @observable userId='';
    @observable canView = false;
    @observable onlyView = false;


    constructor() {
    }
    @observable params;
    @action
    initTabDatas = (params = {}) => {
      this.loading = true;
      this.params = params;
      Apis.getCustomerTab(params).then((data) => {
        this.initTabDatasCallBack(data, params);
      });
    }
    @action
    getFormCondition = () => {
      Apis.getFormCondition({ showlevel: 1 }).then((data) => {
        if (data.status == 'success') {
          this.shareCondition = data.data;
        }
      });
    }
    @action
    initTabDatasCallBack = (data, params) => {
      if (data.status == 'success') {
        if (!data.hasright && typeof (data.hasright) !== 'undefined') {
          this.hasRight = data.hasright;
          this.verified = true;
          if (data.showMainCustomer) {
            Modal.confirm({
              title: getLabel(15172, '系统提示'),
              content: data.msgcode,
              onOk() {
                window.close();
                window.crmOpenPage(`/main/crm/customerView?customerId=${data.mainCustomerID}`);
              },
              onCancel() { window.close(); },
            });
          }
        } else {
          this.hasRight = true;
          this.verified = true;
          this.tabDatas = data.datas;
          this.customerId = params.customerId;
          this.customerName = data.customerName;
          this.rightLevel = data.rightLevel;
          this.loading = false;
          const that = this;
          this.detailTabKey = (function () {
            let key = '1';
            let detailTab = {};
            data.datas && data.datas.map((item) => {
              if (item.default) {
                key = item.id;
                detailTab = { key: item.id, shortname: item.shortname };
              }
            });
            that.detailTab = detailTab;
            return key;
          }());
        }
      } else {
        message.error(getLabel(83437, '出现错误！') + data.msgcode);
      }
    }

    @action
    initCrmInfo = (params) => {
      this.form = new WeaForm();
      this.clearRightMenu();
      this.loadingInfo = true;
      this.currentPageState = 'readOnly';
      Apis.getCustomerView({ ...params, ...this.params }).then((data) => {
        this.loadingInfo = false;
        this.initCrmInfoCallBack(data, params);
      });
    }

    @action
    initCrmInfoCallBack = (data, params) => {
      if (data.status == 'success') {
        this.user = data.user;
        this.conditioninfoEdit = data.datas;
        if (this.rightLevel >= 1 && this.currentPageState == 'readOnly') {
          this.conditioninfoRead = JSON.parse(JSON.stringify(data.datas)); // deep copy
          for (const cg of this.conditioninfoRead) {
            for (const item of cg.items) {
              item.viewAttr = 1;
            }
          }
          this.conditioninfo = this.conditioninfoRead;
        }
        this.contacterInfo = data.contacterInfo;
        if (data.contacterInfo.enableContacter) {
          this.contacterData = toJS(data.contacterInfo.columnsData).map(d => ({ ...d }));
        }
        this.customerId = params.customerId;
        this.rightMenu = data.rcList;
        this.userId = data.loginid;
        this.canView = data.canView;
        this.onlyView = data.onlyview;

        this.form && !this.form.isFormInit && this.form.initFormFields(data.datas);
      } else {
        message.error(getLabel(83437, '出现错误！') + data.msgcode);
      }
    }

    // 联系人信息
    // getContacterInfo=(params={})=>{
    //     Apis.getContacterCard({...params,from:"base",pageSize:50}).then((data) => {
    // 		if(data.status=="success"){
    // 			// this.contacterData = data.datas.rsList;
    // 		}else{
    // 			 message.error('操作失败,'+data.msgcode+"!");
    // 		}
    // 	});
    // }

    // 基本信息编辑
    customerInfoEdit = (params = {}) => {
      const that = this;
      if (params.fieldName == 'type') {
        // 更改客户类型后重新加载页面
        Modal.confirm({
          title: '信息确认',
          content: '您更改了客户类型，页面将重新加载，确定要这样做吗？',
          onOk() {
            that.loading = true;
            Apis.editCustomerInfo(params).then((data) => {
              that.loading = false;
              if (data.status == 'success') {
                message.success(getLabel(83551, '保存成功！'));
                that.initCrmInfo({ customerId: that.customerId });
              } else {
                message.error(getLabel(83437, '出现错误！') + data.msgcode);
              }
            });
          },
          onCancel() {
            // 恢复更改前的值
            that.setFieldValue(params.fieldName, params.oldValue, params.oldValueSpan, params.fieldType);
          },
        });
      } else {
        that.loading = true;
        Apis.editCustomerInfo(params).then((data) => {
          that.loading = false;
          if (data.status == 'success') {
            // 刷新tab页
            if (params.fieldName == 'name') {
              this.initTabDatas({ customerId: this.customerId });
            }
            message.success(getLabel(83551, '保存成功！'));
            that.setFieldValueOld(params.fieldName, params.newValue);
          } else {
            message.error(getLabel(83437, '出现错误！') + data.msgcode);
          }
        });
      }
    }
    // 客户名称重复校验
    customerRepeatCheck = (params = {}) => {
      Apis.customerRepeatCheck(params).then((data) => {
        if (data.status == 'success') {
          const checkResult = data.datas;
          if (checkResult) {
            this.customerInfoEdit(params);
          } else {
            message.error(getLabel('512825', '该客户已存在，请重新输入！'));
          }
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 重置主联系人单选按钮
    @action
    resetMainContacter = (record) => {
      const datas = toJS(this.contacterInfo.columnsData);
      const _datas = datas.map(d => ({ ...d }));
      for (const _data of _datas) {
        if (_data.id == record.id) {
          _data.main = 1;
        } else {
          _data.main = 0;
        }
      }
      this.contacterInfo.columnsData = _datas;
    }

    @action
    updateContacterData = (_datas) => {
      this.contacterInfo.columnsData = _datas;
    }

    @action
    synContacterData = (index, fieldName, value) => {
      this.contacterInfo.columnsData[index][fieldName] = value;
    }

    // 联系人实时编辑
    editContracterData = (params) => {
      const that = this;
      if (params.columns) {
        const columnsTemp = params.columns;
        for (let i = 0; i < columnsTemp.length; i++) {
          columnsTemp[i] = { dataIndex: columnsTemp[i].dataIndex };
        }
        params.columns = columnsTemp;
      }
      const para = { info: JSON.stringify(params) };
      that.loading = true;
      Apis.editContracterData(para).then((data) => {
        that.loading = false;
        if (data.status == 'success') {
          if (params.id) {
            // 已有数据实时编辑
            message.success(getLabel(83551, '保存成功！'));
            // 更新对比数据
            that.contacterData[params.index][params.fieldName] = params.fieldValue;
          } else {
            // 新增数据重新加载
            this.initCrmInfo({ customerId: params.columnsData.customerId });
            // this.getContacterInfo({from:"all",customerId:params.customerId,pageSize:50});
          }
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    changeTab = (key) => {
      this.detailTabKey = key;
      // if(key == "1"){
      // if (key == this.detailTab.key && this.detailTab.shortname == "baseinfo") {
      // this.initCrmInfo({ customerId: this.customerId });
      // this.getContacterInfo({from:"all",customerId:this.customerId,pageSize:50});

      //  }
    }
    // 获取消息提醒信息
    getRemindInfo = (id) => {
      API_CONTACT.getRemindInfo({ customerId: id }).then((data) => {
        if (data.status == 'success') {
          this.remindInfo = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 保存消息提醒
    saveContactRemind = (params) => {
      API_CONTACT.saveRemindSetting(params).then((data) => {
        if (data.status == 'success') {
          return true;
        }
        message.error(getLabel(83437, '出现错误！') + data.msgcode);
      });
    }
    // 共享设置-----------
    getShareSettingList = (params = {}) => {
      this.loading = true;
      Apis.getShareList(params).then((data) => {
        if (data.status == 'success') {
          this.loading = false;
          if (!data.hasright && typeof (data.hasright) !== 'undefined') {
            this.shareAuth = {
              hasRight: false,
              verified: true,
            };
          } else {
            this.shareAuth = {
              hasRight: true,
              verified: true,
            };
            this.shareTableStore.getDatas(data.sessionkey, params.current || 1);
            this.dataKey = data.sessionkey;
          }
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    getShareSettingRightMenu = (params = {}) => {
      this.clearRightMenu();
      Apis.getRightMenuList(params).then((data) => {
        if (data.status == 'success') {
          this.rightMenu = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 删除
    shareSettingDelete = (params = {}, crmid) => {
      const that = this;
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83600, '您确认要删除吗？'),
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
        onOk() {
          Apis.deleteShareList(params).then((data) => {
            if (data.status == 'success') {
              that.getShareSettingList({ customerId: crmid });
            } else {
              message.error(getLabel(83437, '出现错误！') + data.msgcode);
            }
          });
        },
        onCancel() { },
      });
    }
    // 添加共享
    saveShareSetting = (params = {}) => {
      // console.log(params);
      const sharetype = params.sharetype;
      if (sharetype == '6') {
        const jobtitlelevel = parseInt(params.jobtitlelevel);
        params.jobtitlelevel = (jobtitlelevel - 1);
      }
      if (sharetype == '3') {
        const rolelevel = parseInt(params.rolelevel);
        params.rolelevel = (rolelevel - 1);
      }
      Apis.saveShareList(params).then((data) => {
        if (data.status == 'success') {
          this.getShareSettingList({ customerId: params.customerId });
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 修改记录 --------
    getViewLogList = (params = {}) => {
      this.loading = true;
      // 获取表单的参数值
      // const searchParamsAd = this.viewlogForm.getFormParams();
      // const newParams = { customerId: this.customerId, ...searchParamsAd, ...params };
      Apis.getViewLogList(params).then((data) => {
        if (data.status == 'success') {
          this.loading = false;
          if (!data.hasright && typeof (data.hasright) !== 'undefined') {
            this.modifyAuth = {
              hasRight: false,
              verified: true,
            };
          } else {
            this.modifyAuth = {
              hasRight: true,
              verified: true,
            };
            this.modifyTableStore.getDatas(data.sessionkey, params.current || 1);
            this.dataKey = data.sessionkey;
          }
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    getViewLogCondition = (params = {}) => {
      Apis.getViewLogCondition(params).then((data) => {
        if (data.status == 'success') {
          this.viewlogCondition = data.datas;
          // this.viewlogForm && !this.viewlogForm.isFormInit && this.viewlogForm.initFormFields(data.datas);
        } else {
          message.error(`请求高级搜索列表失败,${data.msgcode}!`);
        }
      });
    }
    getViewLogRightMenu = (params) => {
      this.clearRightMenu();
      Apis.getRightMenuList(params).then((data) => {
        if (data.status == 'success') {
          this.rightMenu = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    setShowSearchAd = (bool) => {
      this.showSearchAd = bool;
    }
    // 客户价值-------
    getEvaluationStandard = (params) => {
      Apis.getEvaluationStandard(params).then((data) => {
        if (data.status == 'success') {
          this.evalStandard = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    getEvaluationInfo = (params) => {
      this.loading = true;
      Apis.getEvaluationInfo(params).then((data) => {
        this.getEvaluationInfoCallBack(params, data);
      });
    }

    @action
    getEvaluationInfoCallBack = (params, data) => {
      if (data.status == 'success') {
        this.loading = false;
        if (!data.hasright && typeof (data.hasright) !== 'undefined') {
          this.evalAuth = {
            hasRight: false,
            verified: true,
          };
        } else {
          this.evalAuth = {
            hasRight: true,
            verified: true,
          };
          this.evalDataSources = data.datas;
        }
      } else {
        message.error(getLabel(83437, '出现错误！') + data.msgcode);
      }
    }
    getEvalRightMenu = (params) => {
      this.clearRightMenu();
      Apis.getRightMenuList(params).then((data) => {
        if (data.status == 'success') {
          this.rightMenu = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    saveCustomerEvalData = (data, params) => {
      this.evalDataSources = data;
      this.evalParams = params;
    }
    evaluationUpdate = (params = {}) => {
      Apis.evaluationUpdate(params).then((data) => {
        if (data.status == 'success') {
          this.getEvaluationInfo({ customerId: params.customerId });
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }


    // 脏数据清理
    clearStatus = () => {
      // 客户价值
      this.evalStandard = [];
      this.evalDataSources = [];
      this.evalDataSources = [];
      this.evalParams = {};
    }
    clearRightMenu = () => {
      this.rightMenu = [];
    }

    @action
    setFieldValue = (fieldName, fieldValue, fieldValueSpan, fit) => {
      try {
        const field = {};
        if (fit == 'BROWSER') {
          field[fieldName] = { value: fieldValue, valueSpan: fieldValueSpan };
        } else {
          field[fieldName] = { value: fieldValue };
        }
        this.form.updateFields(field, false);
      } catch (error) {
        // 表单中找不到字段的情况
      }
    }

    resetEmail(fieldName, fieldValue) {
      this.setFieldValue(fieldName, fieldValue);
    }
    resetUrl(fieldName, fieldValue) {
      this.setFieldValue(fieldName, fieldValue);
    }

    setFieldValueOld(fieldName, fieldValue) {
      const conditioninfo = this.conditioninfo;
      for (let i = 0; i < conditioninfo.length; i++) {
        const items = conditioninfo[i].items;
        for (let j = 0; j < items.length; j++) {
          const item = items[j];
          const name = item.domkey[0];
          if (fieldName == name) {
            item.value = fieldValue;
          }
        }
      }
    }

    @action
    extendHandle = (key, title, url, issystem, shortname) => {
      const _tabDatas = toJS(this.tabDatas);
      let finded = false;
      for (const tab of _tabDatas) {
        if (tab.key == key) {
          finded = true;
          break;
        }
      }
      if (!finded) {
        if (typeof (shortname) === 'undefined') {
          shortname = '';
        }
        _tabDatas.push({ id: key, key, title, mainTitle: title, linkurl: url, shortname, editable: true });
        this.tabDatas = _tabDatas;
      }
      this.changeTab(key);
    }

    @action
    onTabEdit = (tabKey, type) => {
      const _tabDatas = toJS(this.tabDatas);
      if (type === 'remove') {
        this.tabDatas = _tabDatas.filter(t => t.key != tabKey);
        this.changeTab(_tabDatas[0].key);
      }
    }

    @action
    editHandle() {
      if (this.currentPageState == 'readOnly') {
        this.currentPageState = 'edit';
        this.conditioninfo = this.conditioninfoEdit;
      } else {
        this.currentPageState = 'readOnly';
        this.conditioninfo = this.conditioninfoRead;
      }
    }
    @action
    setAddressInfo=(district) => {
      Apis.getAddressInfo({ district }).then((data) => {
        this.form.updateFields(data.datas);
      });
    }


    @observable logType;
    @observable logSmallType;
    @observable targetId;
    @observable detailVisible = false;
    @observable detailRecord = {};
    @observable showParams = false;
    @observable detailKey = `${new Date().getTime()}`;
    @observable detailTitle = '';
    @observable viewdetailColums = [];
    @observable viewdetailDatas = [];
    @observable viewdetailTitles = [];

    @action
    update = (object) => {
      if (Object.prototype.toString.call(object) === '[object Object]') {
        for (const key in object) {
          if (object.hasOwnProperty(key)) {
            this[key] = object[key];
          }
        }
      }
      return this;
    };


    setDetailVisible(bool) {
      this.detailVisible = bool;
    }

    setDetailTitle(name = '') {
      this.detailTitle = name;
    }

    setDetailRecord(obj = {}) {
      this.detailRecord = { ...obj };
    }

    setShowParams(bool = false) {
      this.showParams = bool;
    }

    updateDetailkey(key = '') {
      this.detailKey = key;
    }
}

// export const customerCardStore = new CustomerCardStore();
